package Controller;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import DTO.Paciente;
import DTO.Receta;
import DTO.Recomendacion;
import Model.conexionBD;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.html.simpleparser.StyleSheet;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPCellEvent;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPTableEvent;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.PrintWriter;
import java.io.StringReader;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.annotation.WebServlet;


/**
 *
 * @author Edwin
 */
@WebServlet(name = "GeneradorPDF", urlPatterns = {"/GeneradorPDF"})
public class GeneradorPDF extends HttpServlet implements PdfPCellEvent, PdfPTableEvent {

    Font font = null;
    conexionBD c = null;
    List<Receta> lista_medicamentos = new ArrayList();
    List<Recomendacion> lista_recomendaciones = new ArrayList();
    Paragraph footer = null;
    SimpleDateFormat patron = null;
    String hmtl = "";
    
    
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        String cedula = request.getParameter("cedula");
         patron = new SimpleDateFormat("dd/MM/yyyy, hh:mm a");
        try {

            // Texto que va a ser añadido al pdf
            String infoDoctor = "DR. " + "WALTER A. VEGA GÓMEZ\n"
                    + "MÉDICO CIRUJANO\n"
                    + "Especialista en Cirugía General\n"
                    + "Laparoscopía de Vesícula - Aparato Digestivo - Cáncer Gástrico\n"
                    + "Hospital La Católica Tel.: 2246-3282\n"
                    + "E-mail: wvega02@gmail.com\n";
            //  + "Fecha: " + patron.format(new Date());
            font = new Font(Font.FontFamily.TIMES_ROMAN, 14); // name & point size 
            Paragraph header = new Paragraph(infoDoctor, font);
            header.setAlignment(Paragraph.ALIGN_CENTER);
            header.setKeepTogether(true); //ajustar el texto
            header.setSpacingAfter(30); // dar espacio después del párrafo
            header.setLeading(17); //establecer el espacio entre líneas

            c = new conexionBD("root", "root", "SAPCOMED_DATABASE");
            Paciente paciente = c.obtenerPaciente(Integer.parseInt(cedula));
            String infoPaciente = "Sr.(a): " + paciente.getNombre() + " " + paciente.getPrimerApellido() + " " + paciente.getPrimerApellido() + "     "
                    + "Cédula.: " + paciente.getId_Paciente() + "\n" 
                    + "Fecha: " + patron.format(new Date());

            Paragraph info = new Paragraph(infoPaciente, font);
            info.setLeading(18);

           String foot = ""
                    + "________________________"
                    + "\nFirma\n"
                    + "Código: 2157";
             footer = new Paragraph(foot, font);
             footer.setAlignment(Paragraph.ALIGN_CENTER);
//             footer.setSpacingBefore(173);
             footer.setLeading(15);


            Document document = new Document(); //  Creamos el documento
            /*document.setPageSize(PageSize.A4.rotate());
             *document.setPageSize(new Rectangle(15*25,30*20));*/
            document.setPageSize(PageSize.A4);


            // Creamos un ByteArrayOutputStream
            // todo lo que se escriba en el documento
            // se escribe tambien en el ByteArrayOutputStream
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfWriter.getInstance(document, baos);


            document.open(); // Abrimos el documento

            // Escribimos
            String relativeWebPath = "/img/vara_esculapio.jpg";
            String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
            Image image1 = Image.getInstance(absoluteDiskPath);
            image1.setAlignment(Image.LEFT | Image.TEXTWRAP);

            document.add(image1);
            document.add(header);
            document.add(info);

            font = new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.BOLD);
            lista_medicamentos = c.obtenerReceta(Integer.parseInt(cedula));
            if (!lista_medicamentos.isEmpty()) {
                document.add(new Paragraph("\n\n       Receta\n", font));
                document.add(new Paragraph("       Rx:\n", font));
                document.add(createTableMedicamentos(lista_medicamentos));
            }


            lista_recomendaciones = c.obtenerRecomendaciones(Integer.parseInt(cedula));
            if (!lista_recomendaciones.isEmpty()) {
                document.add(createTableRecomendaciones(lista_recomendaciones, document));
            }

            document.add(new Paragraph());

            // Cerramos
            document.close();

            PdfReader reader = new PdfReader(baos.toByteArray());
            // Create a stamper
            PdfStamper stamper = new PdfStamper(reader, baos);
            // Loop over the pages and add a header to each page
            int n = reader.getNumberOfPages();
            for (int i = 1; i <= n; i++) {
                getHeaderFooterTable(i, n).writeSelectedRows(
                        0, -1, 34, 803, stamper.getOverContent(i));
            }
            // Close the stamper
            stamper.close();
            reader.close();

            // Hay que configurar las cabeceras para que
            //el navegador detecte que es un pdf
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setHeader("Content-Disposition", "inline; filename=\"Receta Médica.pdf\"");
            // Configuramos el content type
            response.setContentType("application/pdf");

            // Tamaño
            response.setContentLength(baos.size());

            // Esccribir el ByteArrayOutputStream a el ServletOutputStream
            OutputStream os = response.getOutputStream();
            baos.writeTo(os);
            os.flush();
            os.close();

        } catch (SQLException ex) {
            Logger.getLogger(GeneradorPDF.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(GeneradorPDF.class.getName()).log(Level.SEVERE, null, ex);
        } catch (com.itextpdf.text.DocumentException e) {
            throw new IOException(e.getMessage());
        }
    }

    public PdfPTable createTableRecomendaciones(List<Recomendacion> lista_recomendaciones, Document document)
            throws DocumentException, IOException {
        font = new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.BOLD);
        PdfPTable table = new PdfPTable(new float[]{5});
        table.setWidthPercentage(90f);
        PdfPCell cell;

        cell = new PdfPCell(new Phrase("Indicaciones / Recomendaciones / Nota referencial", font));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setGrayFill(0.9f);
        cell.setMinimumHeight(25f);
        table.addCell(cell);
         String indicaciones ="";
        for (int i = 0; i < lista_recomendaciones.size(); i++) {
             indicaciones  = lista_recomendaciones.get(i).getDescripcion()+"\n\n";

            cell = new PdfPCell(new Paragraph(indicaciones));
            cell.disableBorderSide(PdfPCell.BOX);
            cell.enableBorderSide(PdfPCell.RIGHT);
            cell.enableBorderSide(PdfPCell.LEFT);
            if (i == lista_recomendaciones.size() - 1) {
                cell.enableBorderSide(PdfPCell.BOTTOM);
            }
            cell.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
            table.addCell(cell);
        }
        table.setSpacingBefore(15);
        table.setSpacingAfter(15);
        return table;
    }

    public PdfPTable createTableMedicamentos(List<Receta> lista_medicamentos)
            throws DocumentException, IOException {

        font = new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.BOLD);
//        PdfPTable table = new PdfPTable(new float[]{2, 2, 2});
        PdfPTable table = new PdfPTable(3);
        float[] columnWidths = new float[] {18f, 20f, 30f};
        table.setWidths(columnWidths);
        table.setTableEvent(new GeneradorPDF());
        table.setWidthPercentage(90f);
        table.getDefaultCell().setPadding(5);
        table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
        table.setSpacingBefore(15);
        table.setSpacingAfter(10);
        table.getDefaultCell().setCellEvent(new GeneradorPDF());
        PdfPCell cell;

        cell = new PdfPCell(new Phrase("Medicamento", font));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setMinimumHeight(25f);
        cell.setGrayFill(0.9f);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("Cantidad", font));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setGrayFill(0.9f);
        cell.setMinimumHeight(25f);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("Indicaciones", font));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setGrayFill(0.9f);
        cell.setMinimumHeight(25f);
        table.addCell(cell);

        table.getDefaultCell().setBackgroundColor(null);
        table.setHeaderRows(1);

        for (int i = 0; i < lista_medicamentos.size(); i++) {
            cell = new PdfPCell(new Phrase(lista_medicamentos.get(i).getNombreMedicamento()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setMinimumHeight(30f);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(lista_medicamentos.get(i).getCantidadConsumo()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setMinimumHeight(30f);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(lista_medicamentos.get(i).getDescripcionIndicacion()+"\n\n"));
            cell.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
            cell.setMinimumHeight(30f);
            table.addCell(cell);
      }
        return table;
    }

    public PdfPTable getHeaderFooterTable(int x, int y) {
       // patron = new SimpleDateFormat("dd/MM/yyyy, hh:mm a");

        PdfPTable table = new PdfPTable(1);
        table.setTotalWidth(527);
        table.setLockedWidth(true);
        table.getDefaultCell().setFixedHeight(720);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER); //Rectangle.BOX
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
        //table.addCell(patron.format(new Date()));
        table.addCell(" ");

        // table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
       // table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(footer);

        return table;
    }

    @Override
    public void cellLayout(PdfPCell cell, Rectangle position,
            PdfContentByte[] canvases) {
        float x1 = position.getLeft() + 2;
        float x2 = position.getRight() - 2;
        float y1 = position.getTop() - 2;
        float y2 = position.getBottom() + 2;
        PdfContentByte canvas = canvases[PdfPTable.LINECANVAS];
        canvas.rectangle(x1, y1, x2 - x1, y2 - y1);
        canvas.stroke();
    }

    @Override
    public void tableLayout(PdfPTable table, float[][] width, float[] height,
            int headerRows, int rowStart, PdfContentByte[] canvas) {
        float widths[] = width[0];
        float x1 = widths[0];
        float x2 = widths[widths.length - 1];
        float y1 = height[0];
        float y2 = height[height.length - 1];
        PdfContentByte cb = canvas[PdfPTable.LINECANVAS];
        cb.rectangle(x1, y1, x2 - x1, y2 - y1);
        cb.stroke();
        cb.resetRGBColorStroke();
    }
}
